
<?php

class before1 {
	public static function handler($request, Closure $next)
	{
		echo "请求前一<br/>";
		$response = $next($request);
		return $response;
	}
}

class before2 {
	public static function handler($request, Closure $next)
	{
		echo "请求前二<br/>";
		$response = $next($request);
		return $response;
	}
}

class after1 {
	public static function handler($request, Closure $next)
	{
		echo "请求后一<br/>";
		$response = $next($request);
		return $response;
	}
}

class after2 {
	public static function handler($request, Closure $next)
	{
		echo __ClASS__."请求后二<br/>";
		$response = $next($request);
		return $response;
	}
}

class controller {
	public static function index($request, $next)
	{
		var_dump($request);
		echo "__控制器__<br/>";
		$arr = [
			"name" => "keweite",
			"alis" => "科威特"
		];
		return $arr;
	}
}

class middleWare {

	protected static $queues = [];

	public static function init()
	{
		self::$queues[] = [[before1::class, 'handler'], null];
		self::$queues[] = [[before2::class, 'handler'], null];
		self::$queues[] = [[after1::class, 'handler'], null];
		self::$queues[] = [[after2::class, 'handler'], null];
		self::$queues[] = [[controller::class, 'index'], null];
	}

	public static function dispatch($request)
	{
		return call_user_func(self::resolve(), $request);
	}

	// 溶解,返回闭包，递归
	public static function resolve()
	{
		return function ($request) {
			$queue = array_shift(self::$queues);
			if ($queue != null) {
				list($call, $param) = $queue;
				return call_user_func_array($call, [$request, self::resolve()]);
			}
		};
	}

}


$request = "test";
//$middlewareBean = new middleWare();

middleWare::init();
$res = middleWare::dispatch($request);
var_dump($res);die;
//var_dump($list);die;

?>